import React, { useState, useRef, useEffect } from 'react';
import { LockOutlined, UserOutlined, SafetyCertificateOutlined } from '@ant-design/icons';
import { message, Modal } from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { history, FormattedMessage, useModel, useIntl } from 'umi';
import { login } from '@/services/cpasRequest';
import { getJson, isIEBrowser } from '@/utils';
import styles from './index.less';
import './index.less';
import logoImage from '@/assets/images/Logo1.png';
import backgroundImage from '@/assets/images/logo2Bg4.png';
import formImage from '@/assets/images/logo2Form4.png';

export type LoginProps = {
  themeType: 1;
};

function randomNum(min: number, max: number) {
  return Math.floor(Math.random() * (max - min) + min);
}

const Login: React.FC = () => {
  const [submitting, setSubmitting] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const codeCanvas = useRef<HTMLCanvasElement>(null);
  const [failedCount, setFailedCount] = useState(0);
  const [codeVisible, setCodeVisible] = useState(false);
  const [hasAlreadyLogin, setHasAlreadyLogin] = useState(false);
  const [loginForm] = ProForm.useForm();
  let verifyCode = '';

  const { initialState, setInitialState } = useModel('@@initialState');

  const intl = useIntl();

  const createCode = () => {
    const ctx = codeCanvas.current?.getContext('2d');
    if (!ctx) return;
    const chars = [
      '1',
      '2',
      '3',
      '4',
      '5',
      '6',
      '7',
      '8',
      '9',
      'a',
      'b',
      'c',
      'd',
      'e',
      'f',
      'g',
      'h',
      'j',
      'k',
      'l',
      'm',
      'n',
      'p',
      'q',
      'r',
      's',
      't',
      'u',
      'v',
      'w',
      'x',
      'y',
      'z',
      'A',
      'B',
      'C',
      'D',
      'E',
      'F',
      'G',
      'H',
      'J',
      'K',
      'L',
      'M',
      'N',
      'P',
      'Q',
      'R',
      'S',
      'T',
      'U',
      'V',
      'W',
      'X',
      'Y',
      'Z',
    ];
    let code = '';
    ctx.clearRect(0, 0, 80, 39);
    for (let i = 0; i < 4; i += 1) {
      const char = chars[randomNum(0, 57)];
      code += char;
      ctx.font = `${randomNum(20, 25)}px SimHei`;
      ctx.fillStyle = '#444';
      ctx.textBaseline = 'middle';
      ctx.shadowOffsetX = randomNum(-3, 3);
      ctx.shadowOffsetY = randomNum(-3, 3);
      ctx.shadowBlur = randomNum(-3, 3);
      ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
      const x = (80 / 5) * (i + 1) - 5;
      const y = 39 / 2;
      const deg = randomNum(-25, 25);
      ctx.translate(x, y);
      ctx.rotate((deg * Math.PI) / 180);
      ctx.fillText(char, 0, 0);
      ctx.rotate((-deg * Math.PI) / 180);
      ctx.translate(-x, -y);
    }
    verifyCode = code;
  };

  const goto = () => {
    if (!history) return;
    // setTimeout(() => {
    // const { query } = history.location;
    // const { redirect } = query as { redirect: string };
    // history.push(redirect || '/');
    if (isIEBrowser()) {
      setTimeout(() => {
        history.push('/home');
      }, 100);
    } else {
      history.push('/home');
    }
    // }, 10);
  };

  const handleSubmit = async (values: any) => {
    // console.log('init state: ', initialState);
    if (submitting) return;
    setSubmitting(true);
    try {
      // 登录
      if (codeVisible && values.code.toUpperCase() !== verifyCode.toUpperCase()) {
        message.error(
          intl.formatMessage({
            id: 'p.login.verifyCodeError',
            defaultMessage: '验证码错误，请重新输入。',
          }),
        );
        setSubmitting(false);
        return;
      }
      const loginHeader = initialState?.settings.loginHeader || {};
      const data = await login(values, loginHeader);
      if (data.ok) {
        // if (!values.fromAutoLogin) {
        message.success(
          intl.formatMessage({ id: 'p.login.loginSuccess', defaultMessage: '登录成功！' }),
        );
        // } else {
        //   message.success(
        //     intl.formatMessage({ id: 'p.login.alreadyAutoLogined', defaultMessage: '已自动登录' }),
        //   );
        // }

        const conf = await getJson('settings', './');
        // if (conf.logo) {
        //   conf.logo = './' + conf.logo;
        // }

        setInitialState({
          ...initialState,
          curUser: { ...data.data, password: values.password },
          settings: conf,
          sysName: 'main', // 'audit',
        });
        // if (values.autoLogin) {
        //   localStorage.setItem(
        //     'loginInfo',
        //     JSON.stringify({
        //       username: values.username,
        //       password: values.password,
        //     }),
        //   );
        // }
        localStorage.setItem('password', values.password);
        setHasAlreadyLogin(true);
        goto();
        return;
      }
      message.error(data.data);
      // localStorage.removeItem('loginInfo');
      setFailedCount(failedCount + 1);
      if (failedCount >= 3) {
        setCodeVisible(true);
      }
      // 如果失败去设置用户错误信息
      // setUserLoginState(msg);
    } catch (error) {
      const defaultloginFailureMessage = intl.formatMessage({
        id: 'p.login.loginFailure',
        defaultMessage: '登录失败，请重试！',
      });
      // localStorage.removeItem('loginInfo');
      message.error(defaultloginFailureMessage);
    }
    setSubmitting(false);
  };

  // const { status, type: loginType } = userLoginState;

  useEffect(() => {
    if (hasAlreadyLogin) return;
    createCode();
    // const localLoginInfo = localStorage.getItem('loginInfo');
    // let loginInfo = null;
    // if (localLoginInfo) {
    //   loginInfo = JSON.parse(localLoginInfo);
    // }
    // if (loginInfo) {
    //   loginForm.setFieldsValue({
    //     username: loginInfo.username,
    //     password: loginInfo.password,
    //   });
    //   handleSubmit({
    //     autoLogin: true,
    //     fromAutoLogin: true,
    //     ...loginInfo,
    //   });
    // }
  });

  return (
    <div
      className={styles.container}
      style={{ background: `url("${backgroundImage}")`, backgroundSize: 'cover' }}
    >
      <div className={styles.logo}>
        <img src={logoImage} />
        <span data-v-4a30d4cf="">CPAS电子档案系统</span>
      </div>
      <div className={styles.main} style={{ height: codeVisible ? 440 : 375 }}>
        <div className={styles.title} style={{ background: `url("${formImage}")` }}>
          <img src={logoImage} />
        </div>
        <ProForm
          className="login-form"
          form={loginForm}
          initialValues={{
            autoLogin: true,
          }}
          submitter={{
            searchConfig: {
              submitText: intl.formatMessage({ id: 'p.login.login', defaultMessage: '登录' }),
            },
            render: (_, dom) => dom.pop(),
            submitButtonProps: {
              htmlType: 'submit',
              loading: submitting,
              size: 'large',
              style: {
                width: 320,
              },
            },
          }}
          onFinish={async (values) => {
            handleSubmit(values);
          }}
        >
          {
            <>
              <ProFormText
                name="usercode"
                // name="username"
                width={320}
                style={{
                  borderRadius: 5,
                }}
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'p.login.username',
                  defaultMessage: '用户名',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage={intl.formatMessage({
                          id: 'p.login.pleaseInputUsername',
                          defaultMessage: '请输入用户名!',
                        })}
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                width={320}
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({ id: 'p.login.password', defaultMessage: '密码' })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage={intl.formatMessage({
                          id: 'p.login.pleaseInputPassword',
                          defaultMessage: '请输入密码！',
                        })}
                      />
                    ),
                  },
                ]}
              />
              <ProFormText
                hidden={!codeVisible}
                name="code"
                width={320}
                fieldProps={{
                  size: 'large',
                  prefix: <SafetyCertificateOutlined className={styles.prefixIcon} />,
                  addonAfter: (
                    <canvas onClick={createCode} width="80" height="36" ref={codeCanvas} />
                  ),
                }}
                placeholder={intl.formatMessage({
                  id: 'p.login.verifyCode',
                  defaultMessage: '验证码',
                })}
                rules={[
                  {
                    required: codeVisible,
                    message: (
                      <FormattedMessage
                        id="pages.login.code.required"
                        defaultMessage={intl.formatMessage({
                          id: 'p.login.pleaseInputVerifyCode',
                          defaultMessage: '请输入验证码！',
                        })}
                      />
                    ),
                  },
                ]}
              />
            </>
          }

          <div
            style={{
              marginBottom: 25,
              color: '#fff',
              width: 500,
              height: 20,
              position: 'relative',
            }}
          >
            {/* <div style={{ position: 'absolute', left: 95 }}>
              <ProFormCheckbox noStyle name="autoLogin">
                <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录" />
              </ProFormCheckbox>
            </div> */}
            <div style={{ position: 'absolute', right: 95 }}>
              <a
                style={{
                  float: 'right',
                }}
                onClick={() => setModalVisible(true)}
              >
                <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码?" />
              </a>
            </div>
          </div>
        </ProForm>
        <Modal
          title="忘记密码"
          visible={modalVisible}
          onCancel={() => setModalVisible(false)}
          onOk={() => setModalVisible(false)}
          cancelButtonProps={{ hidden: true }}
        >
          <div className={styles.modal}>
            <p>400-100-1021</p>
            <p>请联系管理员或致电客服</p>
          </div>
        </Modal>
      </div>
    </div>
  );
};

export default Login;
